import { TreeDataTranslate } from '@/utils';

// 自动化导入路由
const views = import.meta.glob('../views/**/*.vue');
const pages = import.meta.glob('../views/**/page.json', {
  eager: true,
  import: 'default'
});

interface Config {
  title: string;
  sort: number;
  parent?: string;
}

const routers = Object.entries(pages).map(([pagePath, config]) => {
  const con = config as Config;
  const path = pagePath.replace('../views', '').replace('/page.json', '');
  const name = pagePath.split('/').slice(-2, -1)[0];
  const compFunc = views[pagePath.replace('page.json', 'index.vue')];

  return {
    path: path,
    name: name,
    parent: con.parent || '',
    component: compFunc,
    meta: con
  };
});

// 转树结构
let routeList = TreeDataTranslate(routers, 'name', 'parent');
routeList.forEach((item: any) => {
  if (item.children && item.children.length > 0) {
    item.children.sort((a: any, b: any) => a.meta.sort - b.meta.sort);
    item.redirect = { name: item.children[0].name };
  }
});

export default routeList;
